package org.musicguardian.core.jobs;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.musicguardian.core.Activator;
import org.musicguardian.core.Core;
import org.musicguardian.core.model.Artist;
import org.musicguardian.core.model.Library;
import org.musicguardian.core.model.RemoteLink;
import org.musicguardian.core.scan.local.DirectoryScanner;
import org.musicguardian.core.scan.remote.MusicBrainzScanner;
import org.musicguardian.core.transactions.LocalLibraryCreateTransaction;
import org.musicguardian.core.transactions.RemoteLinkCreateTransaction;

import entagged.freedb.Freedb;
import entagged.freedb.FreedbQueryResult;

public class JobMusicBrainzScanner extends Job {

    private final Artist artist;

    public JobMusicBrainzScanner(Artist artist) {
	super("Scanning MusicBrainz database for artist " + artist.getName());
	this.artist = artist;
    }

    @Override
    protected IStatus run(final IProgressMonitor monitor) {
	MusicBrainzScanner scanner;
	try {
	    scanner = new MusicBrainzScanner(artist, 50);
	    monitor.beginTask("", scanner.getTotalWork());
	    scanner.addScannerListener(new DirectoryScanner.ScannerListener() {
		public void fileScanned(Object scannedObject) {
		    monitor.worked(1);
		    monitor.setTaskName("Scanning file : "
			    + scannedObject.toString());
		}

	    });
	    RemoteLink[] links = scanner.run().toArray(new RemoteLink[] {});
	    for (int i = 0; i < links.length; i++) {
		RemoteLink remoteLink = links[i];
		Core.getInstance().runTransaction(
			new RemoteLinkCreateTransaction(remoteLink));
	    }
	} catch (Exception e) {
	    return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
		    IStatus.ERROR, "Scanner error", e);
	} finally {
	    monitor.done();
	}
	return Status.OK_STATUS;
    }
}
